package com.suoluo.zenapp.controllers.admin;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Intercepted;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

import com.suoluo.zenapp.common.encrypt.EncryptUtil;
import com.suoluo.zenapp.controllers.admin.user.RandomValidateCode;
import com.suoluo.zenapp.service.user.UserService;

@Path("/")
public class AdminController {

	@Resource(name = "userService")
	private UserService userService;

	@Get("/")
	public String main() {
		return "layout";
	}

	@Intercepted(deny = "login")
	@Post("login")
	public String login(Invocation inv) throws Exception {
		HttpServletRequest req = inv.getRequest();
		String username = req.getParameter("username").trim();
		String password = req.getParameter("password").trim();
		String randomCode = req.getParameter("randomCode").trim();
		String temp = (String) req.getSession().getAttribute(
				"RANDOMVALIDATECODEKEY");
		req.getSession().removeAttribute("RANDOMVALIDATECODEKEY");
		randomCode = randomCode.toUpperCase();
		boolean res = false;
		if (randomCode.equals(temp)) {
			res = userService.findUser(username, EncryptUtil.md5(password));
		}

		if (res) {
			req.getSession().setAttribute("loginUser", username);

			return "layout";
		} else {
			return "login";
		}
	}

	@Intercepted(deny = "login")
	public void verifyCode(Invocation invo) throws Exception {
		HttpServletResponse resp = invo.getResponse();
		HttpServletRequest req = invo.getRequest();
		resp.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
		resp.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expire", 0);
		RandomValidateCode randomValidateCode = new RandomValidateCode();
		try {
			randomValidateCode.getRandcode(req, resp);// 输出图片方法
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
